package com.zyk.scaffold.core.context;

import com.zyk.scaffold.common.basic.BasicConstants;
import com.zyk.scaffold.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
public class ContextHolder{

    public static UserContext getUserContext(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return null;
        }
        String jwtToken = attributes.getRequest().getHeader(BasicConstants.GATEWAY_FILTER_HEADER_JWT_USER_METADATA);
        if(StringUtils.isEmpty(jwtToken)){
            return null;
        }
        UserContext userContext = JwtHelper.getUserContext(jwtToken);
        return userContext;
    }

    public static AppContext getAppContext(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return null;
        }
        String jwtToken = attributes.getRequest().getHeader(BasicConstants.OPEN_API_TOKEN_HEADER);
        if(StringUtils.isEmpty(jwtToken)){
            return null;
        }
        AppContext appContext = JwtHelper.getAppContext(jwtToken);
        return appContext;
    }
}
